<template>
  <fixed-pagination>
    <div class="center">
      <!-- 待审批 -->
      <template v-if="detailInfo.process === 0 ">
        <el-button :disabled="!isExamine" type="danger" plain size="small" class="submit-btn" @click="examineDialog(0)">驳回</el-button>
        <el-button :disabled="!isExamine" type="primary" size="small" class="submit-btn" @click="examineDialog(1)">通过审批</el-button>
      </template>
      <!-- 已审批 -->
      <!-- 结算状态为待上传和待封存和待提交可展示这些按钮 -->
      <template v-if="detailInfo.process === 1 || detailInfo.process === 4 || detailInfo.process === 3">
        <!-- 审批通过 -->
        <export-button
          v-if="detailInfo.process !== 3 && detailInfo.process !==0 && !showMobilePage"
          :export-api="'admin/client/settlement/export'"
          :export-name="'结算单'"
          :query-data="{id: settlementId}"
          :default-loading="false"
          style="margin-right:10px;"
        >
          导出excel
        </export-button>
        <!-- 结算状态为待上传 -->
        <el-button v-if="detailInfo.process === 1" :disabled="!backAuth" type="danger" plain size="small" class="submit-btn" @click="goBack">驳回</el-button>
        <el-button v-if="detailInfo.process === 1" :disabled="!isSubmitSeal" type="primary" size="small" class="submit-btn" @click="toComplate">提交封存</el-button>
        <!-- 结算状态为待封存 -->
        <el-button v-if="detailInfo.process === 4" :disabled="!isComplate" type="primary" size="small" class="submit-btn" @click="toComplate">封存</el-button>
        <el-button v-if="detailInfo.process === 4" :disabled="!isComplate" type="danger" plain size="small" class="submit-btn" @click="rejectSubmitSealDialog()">驳回</el-button>
        <!-- 被驳回就是待提交状态 -->
        <el-button v-if="detailInfo.process === 3" type="primary" size="small" class="submit-btn mobile-btn-flex" @click="editSettle">编辑调整结算单</el-button>
      </template>
      <!-- 已完成 -->
      <template v-if="detailInfo.process === 2">
        <export-button
          v-if="detailInfo.state === 1 && !showMobilePage"
          :export-api="'admin/client/settlement/export'"
          :export-name="'结算单'"
          :query-data="{id: settlementId}"
          :default-loading="false"
          style="margin-right:10px;"
        >
          导出excel
        </export-button>
      </template>
      <el-button v-if="!showMobilePage" type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回</el-button>
      <MoreOpeator
        v-if="showMobilePage"
        :list="[
          {label: '导出excel', exportApi: `admin/client/settlement/export`, auth: (detailInfo.process === 2 && detailInfo.state === 1) || (detailInfo.process === 1 || detailInfo.process === 4), type: 'export', exportName: '结算单', queryData: {id: settlementId} },
          {label: '返回', handelClick: toBack},
        ]"
        label="更多"
        style="margin-left:10px;"
      />
    </div>
    <!-- 提交封存 -->
    <Dialog
      ref="submitSealRef"
      :allDeptList="allDeptList"
      :btn1="'确认'"
      :btn2="'取消'"
      :isShowInput="true"
      summary="请确认是否提交封存"
      title="提交封存确认"
      @handelOK="toSubmitSeal" />
    <!-- 待封存驳回返回上一步 -->
    <Dialog
      ref="rejectSubmitSealRef"
      :allDeptList="allDeptList"
      :btn1="'确认'"
      :btn2="'取消'"
      :isShowInput="true"
      summaryTitle="驳回理由"
      summary="请确认是否驳回上一步骤"
      title="结算单审批确认"
      @handelOK="toExamine" />
    <!-- 驳回 -->
    <Dialog
      ref="rejectDialogRef"
      :allDeptList="allDeptList"
      :btn1="'确认'"
      :btn2="'取消'"
      :isShowInput="true"
      summaryTitle="驳回理由"
      summary="请确认是否驳回结算单 "
      title="结算单审批确认"
      @handelOK="toExamine" />
    <!-- 通过审批 -->
    <Dialog
      ref="passDialogRef"
      :allDeptList="allDeptList"
      :btn1="'确认'"
      :btn2="'取消'"
      summary="请确认是否通过审批"
      title="结算单审批确认"
      @handelOK="toExamine" />
    <createSettle ref="createRef" @getData="getData" />
  </fixed-pagination>
</template>

<script>
import Dialog from './dialog';
// import { format } from '@/filters/date';
import ElMessage from '@/utils/message';
import ExportButton from './exportBtn';
import createSettle from '@/components/Customer/createSettle';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';

import { examineSettlement, settlementBack, closeSettlement, submitSeal } from '@/api/customer';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
export default {
  components: { Dialog, ExportButton, createSettle, MoreOpeator },
  props: {
    detailInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    settlementId: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      clientWidth: '',
      allDeptList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    // 有审批权限
    isExamine() {
      return hasRouteAuth('crm:customer:examine') || this.isAdmin;
    },
    // 驳回
    backAuth() {
      return hasRouteAuth('crm:customer:backSeal') || this.isAdmin;
    },
    // 有提交封存权限
    isSubmitSeal() {
      return hasRouteAuth('crm:customer:submitSeal') || this.isAdmin || this.userInfo.userName === this.detailInfo.createUserName;
    },
    // 有封存权限
    isComplate() {
      return hasRouteAuth('crm:customer:complete') || this.isAdmin;
    },
    clientCompanyName() {
      return this.detailInfo.clientCompany || '--';
    }
  },
  methods: { hasRouteAuth,
    getData() { this.$emit('getData'); },
    examineDialog(status) {
      const defaultObjectUser = [{ id: this.detailInfo.createUserId || 0, userName: this.detailInfo.createUserName || '创建人' }];
      // const time = this.detailInfo.settleStartTime ? format(this.detailInfo.settleStartTim, 'YYYY年MM月') : '';
      let msg = '';
      if (status === 1) {
        msg = `【${this.clientCompanyName}】客户结算单已通过审批，请及时上传单据`;
      } else if (status === 0) {
        msg = `【${this.clientCompanyName}】客户结算单未过审，请及时调整`;
      }
      const dialogref = status === 0 ? this.$refs.rejectDialogRef : this.$refs.passDialogRef;
      dialogref.showDialog({ defaultMsg: msg, defaultObjectUser, extendParams: { status }});
    },
    toExamine(data) {
      data.id = this.settlementId;
      examineSettlement(data).then(res => {
        if (res.code === 200) {
          if (data.status === 0 || data.status === 2) ElMessage.success('驳回成功');
          if (data.status === 1) ElMessage.success('审批成功');
          this.$emit('getData');
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    // 请求提交封存接口
    toSubmitSeal(data) {
      data.id = this.settlementId;
      submitSeal(data).then(res => {
        if (res.code === 200) {
          this.$emit('getData');
          ElMessage.success('提交封存成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {});
    },
    // 待封存驳回上一步弹窗展示
    rejectSubmitSealDialog() {
      const defaultObjectUser = [{ id: this.detailInfo.createUserId || 0, userName: this.detailInfo.createUserName || '创建人' }];
      const msg = `【${this.clientCompanyName}】客户结算单上传单据有误，请及时调整`;
      this.$refs.rejectSubmitSealRef.showDialog({ defaultMsg: msg, defaultObjectUser, extendParams: { status: 2 }});
    },
    toComplate() {
      if (!this.detailInfo.attachment || this.detailInfo.attachment.length === 0) {
        ElMessage.error('请上传单据后再提交封存');
        return;
      }
      // 展示提交封存钉钉通知弹窗
      if (this.detailInfo.process === 1) {
        const defaultObjectUser = [{ id: this.detailInfo.examineUserId || 0, userName: this.detailInfo.examineUserName || '审批人' }];
        const msg = `【${this.clientCompanyName}】客户结算单已上传单据，请及时审批封存`;
        this.$refs.submitSealRef.showDialog({ defaultMsg: msg, defaultObjectUser });
        return false;
      }
      // 以下为封存逻辑
      this.$confirm('确认是否封存结算单<br />封存后将不可编辑', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        dangerouslyUseHTMLString: true,
        center: true
      }).then(() => {
        const params = { id: this.settlementId };
        closeSettlement(params).then(res => {
          if (res.code === 200) {
            this.$emit('getData');
            ElMessage.success('封存成功');
          } else {
            ElMessage.error(res.message);
          }
        });
      }).catch(() => {});
    },
    editSettle() {
      if (this.$refs.createRef) this.$refs.createRef.openDialog(this.detailInfo, true);
    },
    goBack() {
      this.$confirm('请确认是否驳回待审批<br />驳回将会清空附件内容', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        dangerouslyUseHTMLString: true,
        center: true
      }).then(() => {
        const params = { id: this.settlementId };
        settlementBack(params).then(res => {
          if (res.code === 200) {
            this.$emit('getData');
            ElMessage.success('驳回成功');
          } else {
            ElMessage.error(res.message);
          }
        });
      }).catch(() => {});
    },
    toBack() {
      this.$router.push({
        name: 'customersettle',
        params: { }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
}
</style>
